import { useEffect, useMemo, useState, useCallback } from "react";
import TextAear from "@/componets/textAear";
import {
  Container,
  LeftContent,
  RightContent,
  ExpendBtn,
  Result,
  Dragger,
  ActionItem,
  ResultList,
  ResultItem,
} from "./styled";
import { useMouse } from "@/utils/useMouse";
import moment from "moment";
import { message } from "antd";
import { usePresskeyborad } from "@/utils/usePress";

interface resultType {
  createTime: string;
  result: string;
}

const JsBox = () => {
  const { keys } = usePresskeyborad();
  const isCtrS = useMemo(
    () => keys.includes("Control") && keys.includes("s"),
    [keys]
  );
  const [width, setWidth] = useState(400);
  const [height, setHeight] = useState(350);
  const [isPress, setIsPress] = useState(false);
  const [startY, setStartY] = useState(-1);
  const [endY, setEndY] = useState(350);
  const { y } = useMouse();
  const [results, setResults] = useState<resultType[]>([]);
  const [codeVal, setCodeVal] = useState<string>(
    sessionStorage.getItem("code")
      ? String(sessionStorage.getItem("code"))
      : `// 前端示例代码，必须console.log输出\nconsole.log('hello, world!');`
  );

  useEffect(() => {
    isCtrS && saveHandle();
  }, [isCtrS]);

  const mouseDownHandle = (e: any) => {
    const { clientY } = e;
    setStartY(clientY);
    setIsPress(true);
  };

  useEffect(() => {
    if (isPress && startY != -1) {
      setHeight(endY + startY - y);
    }
  }, [height, y, isPress, startY]);

  const mouseUpHandle = (e: any) => {
    setIsPress(false);
    setStartY(-1);
    setEndY(height);
  };
  const saveHandle = () => {
    sessionStorage.setItem("code", codeVal);
    message.success("保存成功");
  };
  const runHandle = () => {
    if (!codeVal) return;
    let createTime = moment(new Date().getTime()).format("YYYY-MM-DD HH:mm:ss");
    console.log = function (value) {
      return value;
    };
    console.log(codeVal);
    const result = eval(codeVal);
    const newResult = JSON.parse(JSON.stringify(results));
    newResult.push({
      createTime,
      result: JSON.stringify(result),
    });
    setResults(newResult);
  };
  const changeVal = useCallback((value: string, viewUpdate: any) => {
    setCodeVal(value);
  }, []);
  return (
    <Container onMouseUp={mouseUpHandle}>
      <LeftContent width={width}>
        <ExpendBtn onClick={() => setWidth(width == 0 ? 400 : 0)}>
          收起
        </ExpendBtn>
      </LeftContent>
      <RightContent>
        <TextAear height={height} onChange={changeVal} codeVal={codeVal} />
        <Result height={height}>
          <Dragger onMouseDown={mouseDownHandle}>
            <ActionItem onClick={saveHandle}>保存(ctr+s)</ActionItem>
            <ActionItem onClick={runHandle}>运行</ActionItem>
            <ActionItem onClick={() => setResults([])}>清空</ActionItem>
          </Dragger>
          <ResultList height={height}>
            {results.map((item, index) => (
              <ResultItem key={index}>
                {item.createTime} : {item.result}
              </ResultItem>
            ))}
          </ResultList>
        </Result>
      </RightContent>
    </Container>
  );
};

export default JsBox;
